from time import sleep

import requests
import pandas as pd
import json

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.69'
}
url_car = 'https://www.dongchedi.com/motor/pc/car/series/car_dealer_price'


def main():
    df = pd.read_csv('../static/data/info.csv')
    car_info_list = []
    for i in df.values.tolist():
        car_info_list += req_car_info(i[2][1:-1].replace(' ', ''), i)
        sleep(0.5)
    save_car_info(car_info_list)


def req_car_info(car_ids, info):
    params = {
        'aid': '1839',
        'app_name': 'auto_web_pc',
        'car_ids': car_ids,
        'city_name': '广州'
    }
    resp_car = requests.get(url_car, headers=headers, params=params)
    json_data = json.loads(resp_car.text)
    data = json_data.get('data', {})
    car_info = []
    for car_id in data:
        car_name = data[car_id].get('car_name', '')
        year = data[car_id].get('year', '')
        official_price = data[car_id].get('official_price', '')
        dealer_price = data[car_id].get('dealer_price', '')
        car_info.append(info + [car_name, year, official_price, dealer_price])
    return car_info


def save_car_info(car_info_list):
    df = pd.DataFrame(car_info_list,
                      columns=['brand_name', 'outter_name', 'car_ids', 'dcar_score', 'dealer_price', 'car_name', 'year',
                               'official_price', 'dealer_price'])
    df.to_csv('../static/data/car_info.csv', index=False)


if __name__ == '__main__':
    main()
